package com.aliang.shopping.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aliang.shopping.config.OssConfig;
import com.aliang.shopping.mapper.AdminMapper;
import com.aliang.shopping.mapper.BusinessMapper;
import com.aliang.shopping.mapper.ContactMapper;
import com.aliang.shopping.mapper.UserInfoMapper;
import com.aliang.shopping.model.converter.ChatConverter;
import com.aliang.shopping.model.po.Contact;
import com.aliang.shopping.model.vo.chat.ContactVO;
import com.aliang.shopping.model.vo.chat.SimpleContactVO;
import com.aliang.shopping.security.auth.UserHolder;
import com.aliang.shopping.service.ContactService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ShiBaLover
 * @description 针对表【contact(联系人表)】的数据库操作Service实现
 * @createDate 2024-10-28 09:35:41
 */
@Service
@AllArgsConstructor
public class ContactServiceImpl extends ServiceImpl<ContactMapper, Contact>
        implements ContactService {

    private final AdminMapper adminMapper;
    private final BusinessMapper businessMapper;
    private final UserInfoMapper userInfoMapper;
    private final ChatConverter chatConverter;
    private final OssConfig ossConfig;

    @Override
    public List<ContactVO> getContactList(String keyword) {
        //获取当前登录用户Id
        Long userId = UserHolder.getUserId();
        //获取全部联系人的Id
        List<Long> contactIds = this.baseMapper.getContactIdsByUserId(userId);
        if (ObjectUtil.isEmpty(contactIds))
            return Collections.emptyList();
        //是否搜索
        if (StrUtil.isNotBlank(keyword)) {
            //要搜索，因为联系人表没有存有名字，所以要连表查询
            contactIds = this.baseMapper.getContactIdsByKeyWord(contactIds, keyword);
        }
        if (ObjectUtil.isEmpty(contactIds))
            return Collections.emptyList();
        // 获取联系人信息
        List<Contact> contactList = this.baseMapper.selectList(new QueryWrapper<Contact>()
                .eq("user_id", userId)
                .in("contact_id", contactIds)
        );
        //转换数据
        List<ContactVO> contactVOList = chatConverter.toContactVOList(contactList);
        // 获取联系人名字和头像数据
        List<SimpleContactVO> simpleContactVOS = this.userInfoMapper.getSimpleContactById(contactIds);
        Map<Long, SimpleContactVO> nameMap = simpleContactVOS.stream().collect(Collectors.toMap(SimpleContactVO::getId, item -> item));
        //设置名字和头像
        contactVOList.forEach(item -> {
            SimpleContactVO simpleContactVO = nameMap.get(item.getId());
            item.setNickname(simpleContactVO.getNickname());
            //返回完整头像路径
            if (StrUtil.isNotBlank(simpleContactVO.getAvatar()))
                item.setAvatar(ossConfig.getUrl() + simpleContactVO.getAvatar());
        });
        return contactVOList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateContactById(ContactVO contact, Long userId, boolean online) {
        //转换po对象
        Contact contactPO = chatConverter.toContactPO(contact);
        //更新用户的联系人信息
        LambdaQueryWrapper<Contact> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Contact::getUserId, userId)
                .eq(Contact::getContactId, contact.getId());
        this.baseMapper.update(contactPO, wrapper);
        //如果不在在线状态，则更新该联系人的未读消息
        if (!online) {
            wrapper.clear();
            wrapper.eq(Contact::getUserId, contact.getId()) //联系人id
                    .eq(Contact::getContactId, userId)
                    .select(Contact::getUnread);
            // 获取联系人信息
            Contact contactDB = this.baseMapper.selectOne(wrapper);
            if (ObjectUtil.isEmpty(contactDB))
                return true;
            // 更新联系人信息
            contactDB.setLastSendTime(contactPO.getLastSendTime());
            contactDB.setLastContent(contactPO.getLastContent());
            contactDB.setUnread(contactDB.getUnread() + 1);
            this.baseMapper.update(contactDB, wrapper);
        }
        return true;
    }

    @Override
    public Integer getUnreadNum(Long userId) {
        return this.baseMapper.getUnreadNum(userId);
    }
}




